home *** CD-ROM | disk | FTP | other *** search
/ MacHack 1994 / MacHack 1994.toast / MacHack™94 / Hacks / [√] May be freely distributed / Keith Stattenfield / MacsbugWindow ƒ / MacsbugWindow.cp < prev    next >
Encoding:
Text File  |  1994-06-25  |  25.3 KB  |  776 lines  |  [TEXT/KAHL]

  1. #include <Limits.h>
  2. #include "MacsbugWindow.h"
  3.  
  4. /* The "g" prefix is used to emphasize that a variable is global. */
  5.  
  6. /* GMac is used to hold the result of a SysEnvirons call. This makes
  7.    it convenient for any routine to check the environment. */
  8. SysEnvRec    gMac;                /* set up by Initialize */
  9.  
  10. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  11.    trap is available. If it is false, we know that we must call GetNextEvent. */
  12. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  13.  
  14. /* GInBackground is maintained by our osEvent handling routines. Any part of
  15.    the program can check it to find out if it is currently in the background. */
  16. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  17.  
  18.  
  19. WindowPtr macsbugWindowP = nil;
  20.  
  21. BitMap macsbugWindowBitMap;
  22.  
  23. WindowPtr gCommandsWindow = nil;
  24.  
  25. unsigned long gLastChecksum = 0;
  26.  
  27.  
  28. /* Here are declarations for all of the C routines. In MPW 3.0 and later we can use
  29.    actual prototypes for parameter type checking. */
  30. void EventLoop( void );
  31. void DoEvent( EventRecord *event );
  32. void AdjustCursor( Point mouse, RgnHandle region );
  33. void GetGlobalMouse( Point *mouse );
  34. void DoUpdate( WindowPtr window );
  35. void DoActivate( WindowPtr window, Boolean becomingActive );
  36. void DoContentClick( WindowPtr window );
  37. void DrawWindow( WindowPtr window );
  38. void AdjustMenus( void );
  39. void DoMenuCommand( long menuResult );
  40. Boolean DoCloseWindow( WindowPtr window );
  41. void Terminate( void );
  42. void Initialize( void );
  43. Boolean GoGetRect( short rectID, Rect *theRect );
  44. void ForceEnvirons( void );
  45. Boolean IsAppWindow( WindowPtr window );
  46. Boolean IsDAWindow( WindowPtr window );
  47. Boolean TrapAvailable( short tNumber, TrapType tType );
  48. void AlertUser( void );
  49. void DoNullEvent ( );
  50.  
  51. /* Define HiWrd and LoWrd macros for efficiency. */
  52. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  53. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  54.  
  55. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  56.    dependency on the ordering of fields within a Rect */
  57. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  58. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  59.  
  60.  
  61.  
  62. /* This routine is part of the MPW runtime library. This external
  63.    reference to it is done so that we can unload its segment, %A5Init. */
  64.  
  65.  
  66. #pragma segment Main
  67. main()
  68. {
  69.     // UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  70.     
  71.     /* 1.01 - call to ForceEnvirons removed */
  72.     
  73.     /*    If you have stack requirements that differ from the default,
  74.         then you could use SetApplLimit to increase StackSpace at 
  75.         this point, before calling MaxApplZone. */
  76.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  77.  
  78.     Initialize();                    /* initialize the program */
  79.     // UnloadSeg((Ptr) Initialize);    /* note that ize must not be in Main! */
  80.     
  81.     Rect r = { 0, 0, 480, 640 };
  82.     macsbugWindowBitMap.baseAddr = (Ptr) 0x17cac62;
  83.     macsbugWindowBitMap.rowBytes = 640 / 8;
  84.     macsbugWindowBitMap.bounds = r;
  85.  
  86.     Rect bounds = { 40, 8, 40 + 480, 8 + 640 };
  87.     macsbugWindowP = NewWindow ( nil, & bounds, "\pMacsbug", true, 0, (WindowPtr) nil, true, 0 );
  88.  
  89.     EventLoop();                    /* call the main event loop */
  90.     
  91.     return 0;
  92. }
  93.  
  94.  
  95. /*    Get events forever, and handle them by calling DoEvent.
  96.     Get the events by calling WaitNextEvent, if it's available, otherwise
  97.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  98.  
  99. #pragma segment Main
  100. void EventLoop()
  101. {
  102.     RgnHandle    cursorRgn;
  103.     Boolean        gotEvent;
  104.     EventRecord    event;
  105.     Point        mouse;
  106.  
  107.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  108.     do {
  109.         /* use WNE if it is available */
  110.         if ( gHasWaitNextEvent ) {
  111.             GetGlobalMouse(&mouse);
  112.             AdjustCursor(mouse, cursorRgn);
  113.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  114.         }
  115.         else {
  116.             SystemTask();
  117.             gotEvent = GetNextEvent(everyEvent, &event);
  118.         }
  119.         gotEvent = true;
  120.         if ( gotEvent ) {
  121.             /* make sure we have the right cursor before handling the event */
  122.             AdjustCursor(event.where, cursorRgn);
  123.             DoEvent(&event);
  124.         }
  125.         /*    If you are using modeless dialogs that have editText items,
  126.             you will want to call IsDialogEvent to give the caret a chance
  127.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  128.             for a non-NIL value before calling IsDialogEvent. */
  129.     } while ( true );    /* loop forever; we quit via ExitToShell */
  130. } /*EventLoop*/
  131.  
  132.  
  133. /* Do the right thing for an event. Determine what kind of event it is, and call
  134.  the appropriate routines. */
  135.  
  136. #pragma segment Main
  137. void DoEvent(EventRecord* event)
  138. {
  139.     short        part, err;
  140.     WindowPtr    window;
  141.     Boolean        hit;
  142.     char        key;
  143.     Point        aPoint;
  144.     Boolean handled = false;
  145.     
  146.     if ( IsDialogEvent ( event ) )
  147.     {    DialogPtr dialogP;
  148.         short itemHit;
  149.         
  150.         handled = DialogSelect ( event, & dialogP, & itemHit );
  151.     }
  152.     
  153.     switch ( event->what ) {
  154.         case mouseDown:
  155.             part = FindWindow(event->where, &window);
  156.             switch ( part ) {
  157.                 case inMenuBar:                /* process a mouse menu command (if any) */
  158.                     AdjustMenus();
  159.                     DoMenuCommand(MenuSelect(event->where));
  160.                     break;
  161.                 case inSysWindow:            /* let the system handle the mouseDown */
  162.                     SystemClick(event, window);
  163.                     break;
  164.                 case inContent:
  165.                     if ( window != FrontWindow() ) {
  166.                         SelectWindow(window);
  167.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  168.                     } else
  169.                         DoContentClick(window);
  170.                     break;
  171.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  172.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  173.                     break;
  174.                 case inGrow:
  175.                     break;
  176.                 case inZoomIn:
  177.                 case inZoomOut:
  178.                     hit = TrackBox(window, event->where, part);
  179.                     if ( hit ) {
  180.                         SetPort(window);                /* the window must be the current port... */
  181.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  182.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  183.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  184.                     }
  185.                     break;
  186.             }
  187.             break;
  188.             
  189.         case keyDown:
  190.         case autoKey:                        /* check for menukey equivalents */
  191.             key = event->message & charCodeMask;
  192.             if ( event->modifiers & cmdKey )
  193.             {            /* Command key down */
  194.                 if ( event->what == keyDown ) {
  195.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  196.                     DoMenuCommand(MenuKey(key));
  197.                 }
  198.             }
  199.             else if ( FrontWindow () == gCommandsWindow )
  200.             {
  201.                 char key = event->message & 0xff;
  202.                 
  203.                 if ( key == 13 )
  204.                 {    short itemType;
  205.                     Handle h;
  206.                     Rect r;
  207.                     Str255 message;
  208.                     
  209.                     GetDItem ( gCommandsWindow, 1, & itemType, & h, & r );
  210.                     GetIText ( h, message );
  211.                                         
  212.                     BlockMove ( & message[1], &message[2], message[0] );
  213.                     
  214.                     message[1] = ';';
  215.                     message[++message[0]] = ';';
  216.                     message[++message[0]] = 'g';
  217.                                         
  218.                     SetIText ( h, "\p" );
  219.                     
  220.                     DebugStr ( message );
  221.                     
  222.                     gLastChecksum ++;
  223.                 }
  224.             }
  225.             break;
  226.             
  227.         case activateEvt:
  228.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  229.             break;
  230.             
  231.         case updateEvt:
  232.             DoUpdate((WindowPtr) event->message);
  233.             break;
  234.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  235.             to a diskEvt, so that the user can format a floppy. */
  236.  
  237. #if 0
  238.         case diskEvt:
  239.             if ( HiWord(event->message) != noErr ) {
  240.                 SetPt(&aPoint, , kDITop);
  241.                 err = DIBadMount(aPoint, event->message);
  242.             }
  243.             break;
  244. #endif
  245.  
  246.         case kOSEvent:
  247.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  248.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  249.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  250.                     gInBackground = (event->message & kResumeMask) == 0;
  251.                     DoActivate(FrontWindow(), !gInBackground);
  252.                     break;
  253.             }
  254.             break;
  255.             
  256.         case nullEvent:
  257.             DoNullEvent ( );
  258.             break;
  259.     }
  260. } /*DoEvent*/
  261.  
  262.  
  263. /*    Change the cursor's shape, depending on its position. This also calculates the region
  264.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  265.     that region, an event would be generated, causing this routine to be called,
  266.     allowing us to change the region to the region the mouse is currently in. If
  267.     there is more to the event than just “the mouse moved”, we get called before the
  268.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  269.     this is called again before we     fall back into WNE. */
  270.  
  271. #pragma segment Main
  272. void AdjustCursor(Point mouse, RgnHandle region)
  273. {
  274.     WindowPtr    window;
  275.     RgnHandle    arrowRgn;
  276.     RgnHandle    plusRgn;
  277.     Rect        globalPortRect;
  278.  
  279.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  280.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  281.         /* calculate regions for different cursor shapes */
  282.         arrowRgn = NewRgn();
  283.         plusRgn = NewRgn();
  284.  
  285.         /* start with a big, big rectangular region */
  286.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  287.  
  288.         /* calculate plusRgn */
  289.         if ( IsAppWindow(window) ) {
  290.             SetPort(window);    /* make a global version of the viewRect */
  291.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  292.             globalPortRect = window->portRect;
  293.             RectRgn(plusRgn, &globalPortRect);
  294.             SectRgn(plusRgn, window->visRgn, plusRgn);
  295.             SetOrigin(0, 0);
  296.         }
  297.  
  298.         /* subtract other regions from arrowRgn */
  299.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  300.  
  301.         /* change the cursor and the region parameter */
  302.         if ( PtInRgn(mouse, plusRgn) ) {
  303.             SetCursor(*GetCursor(plusCursor));
  304.             CopyRgn(plusRgn, region);
  305.         } else {
  306.             SetCursor(&qd.arrow);
  307.             CopyRgn(arrowRgn, region);
  308.         }
  309.  
  310.         /* get rid of our local regions */
  311.         DisposeRgn(arrowRgn);
  312.         DisposeRgn(plusRgn);
  313.     }
  314. } /*AdjustCursor*/
  315.  
  316.  
  317. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  318.     it will return either a pending event or a null event. In either case,
  319.     the where field of the event record will contain the current position
  320.     of the mouse in global coordinates and the modifiers field will reflect
  321.     the current state of the modifiers. Another way to get the global
  322.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  323.     being sure that thePort is set to a valid port. */
  324.  
  325. #pragma segment Main
  326. void GetGlobalMouse(Point* mouse)
  327. {
  328.     EventRecord    event;
  329.     
  330.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  331.     *mouse = event.where;                /* just the mouse position */
  332. } /*GetGlobalMouse*/
  333.  
  334.  
  335. /*    This is called when an update event is received for a window.
  336.     It calls DrawWindow to draw the contents of an application window.
  337.     As an effeciency measure that does not have to be followed, it
  338.     calls the drawing routine only if the visRgn is non-empty. This
  339.     will handle situations where calculations for drawing or drawing
  340.     itself is very time-consuming. */
  341.  
  342. #pragma segment Main
  343. void DoUpdate(WindowPtr window)
  344. {
  345.     if ( IsAppWindow(window) ) {
  346.         BeginUpdate(window);                /* this sets up the visRgn */
  347.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  348.             DrawWindow(window);
  349.         EndUpdate(window);
  350.     }
  351. } /*DoUpdate*/
  352.  
  353.  
  354. /*    This is called when a window is activated or deactivated.
  355.     In Sample, the Window Manager's handling of activate and
  356.     deactivate events is sufficient. Other applications may have
  357.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  358.  
  359. #pragma segment Main
  360. void DoActivate( WindowPtr window, Boolean becomingActive)
  361. {
  362.     if ( IsAppWindow(window) ) {
  363.         if ( becomingActive )
  364.         {
  365.         }
  366.         else
  367.         {
  368.         }
  369.     }
  370. } /*DoActivate*/
  371.  
  372.  
  373. /*    This is called when a mouse-down event occurs in the content of a window.
  374.     Other applications might want to call FindControl, TEClick, etc., to
  375.     further process the click. */
  376.  
  377. #pragma segment Main
  378. void DoContentClick(WindowPtr window)
  379. {
  380. } /*DoContentClick*/
  381.  
  382.  
  383. #pragma segment Main
  384. void DrawWindow(WindowPtr window)
  385. {
  386.     SetPort(window);
  387.  
  388.     if ( window ==  macsbugWindowP )
  389.     {
  390.         CopyBits ( & macsbugWindowBitMap, & window->portBits,
  391.                     & macsbugWindowBitMap.bounds, & macsbugWindowBitMap.bounds,
  392.                     srcCopy, nil );
  393.     }
  394.     else if ( window == gCommandsWindow )
  395.     {
  396.     }
  397.     
  398.  
  399. } /*DrawWindow*/
  400.  
  401.  
  402.  
  403. void DoNullEvent ( )
  404. {
  405.     unsigned long l = 0;
  406.     
  407.     for ( unsigned short i = 0; i < 768; ++ i )
  408.         l += * ( char *) (Ptr) ( 0x17cac62 + i );
  409.         
  410.     if ( l != gLastChecksum )
  411.     {
  412.         SetPort ( macsbugWindowP );
  413.         InvalRect ( & macsbugWindowP->portRect );
  414.     
  415.         gLastChecksum = l;
  416.     }
  417.  
  418. }
  419.  
  420.  
  421. /*    Enable and disable menus based on the current state.
  422.     The user can only select enabled menu items. We set up all the menu items
  423.     before calling MenuSelect or MenuKey, since these are the only times that
  424.     a menu item can be selected. Note that MenuSelect is also the only time
  425.     the user will see menu items. This approach to deciding what enable/
  426.     disable state a menu item has the advantage of concentrating all
  427.     the decision-making in one routine, as opposed to being spread throughout
  428.     the application. Other application designs may take a different approach
  429.     that is just as valid. */
  430.  
  431. #pragma segment Main
  432. void AdjustMenus()
  433. {
  434.     WindowPtr    window;
  435.     MenuHandle    menu;
  436.  
  437.     window = FrontWindow();
  438.  
  439.     menu = GetMHandle(mFile);
  440.     #if 0
  441.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  442.         EnableItem(menu, iClose);
  443.     else
  444.         DisableItem(menu, iClose);    /* but not our traffic light window */
  445.     #endif
  446.     
  447.     menu = GetMHandle(mEdit);
  448.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  449.         EnableItem(menu, iUndo);
  450.         EnableItem(menu, iCut);
  451.         EnableItem(menu, iCopy);
  452.         EnableItem(menu, iClear);
  453.         EnableItem(menu, iPaste);
  454.         EnableItem(menu, iUpdate);
  455.     } else {                        /* …but we don’t use it */
  456.         DisableItem(menu, iUndo);
  457.         DisableItem(menu, iCut);
  458.         DisableItem(menu, iCopy);
  459.         DisableItem(menu, iClear);
  460.         DisableItem(menu, iPaste);
  461.         EnableItem(menu, iUpdate);
  462.     }
  463.  
  464. } /*AdjustMenus*/
  465.  
  466.  
  467. /*    This is called when an item is chosen from the menu bar (after calling
  468.     MenuSelect or MenuKey). It performs the right operation for each command.
  469.     It is good to have both the result of MenuSelect and MenuKey go to
  470.     one routine like this to keep everything organized. */
  471.  
  472. #pragma segment Main
  473. void DoMenuCommand(long menuResult)
  474. {
  475.     short        menuID;                /* the resource ID of the selected menu */
  476.     short        menuItem;            /* the item number of the selected menu */
  477.     short        itemHit;
  478.     Str255        daName;
  479.     short        daRefNum;
  480.     Boolean        handledByDA;
  481.  
  482.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  483.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  484.     switch ( menuID ) {
  485.         case mApple:
  486.             switch ( menuItem ) {
  487.                 case iAbout:        /* bring up alert for About */
  488.                     itemHit = Alert(rAboutAlert, nil);
  489.                     break;
  490.                 default:            /* all non-About items in this menu are DAs */
  491.                     /* type Str255 is an array in MPW 3 */
  492.                     GetItem(GetMHandle(mApple), menuItem, daName);
  493.                     daRefNum = OpenDeskAcc(daName);
  494.                     break;
  495.             }
  496.             break;
  497.             
  498.         case mFile:
  499.             switch ( menuItem ) {
  500.                 case iQuit:
  501.                     Terminate();
  502.                     break;
  503.             }
  504.             break;
  505.             
  506.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  507.             switch ( menuItem )
  508.             {
  509.                 case iUpdate:
  510.                     SetPort ( macsbugWindowP );
  511.                     InvalRect ( & macsbugWindowP->portRect );
  512.                     break;
  513.                 
  514.                 default:
  515.                     handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  516.                     break;
  517.             }
  518.             break;
  519.             
  520.         case mLight:
  521.             switch ( menuItem ) {
  522.             }
  523.             break;
  524.     }
  525.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  526. } /*DoMenuCommand*/
  527.  
  528.  
  529. /* Close a window. This handles desk accessory and application windows. */
  530.  
  531. /*    1.01 - At this point, if there was a document associated with a
  532.     window, you could do any document saving processing if it is 'dirty'.
  533.     DoCloseWindow would return true if the window actually closed, i.e.,
  534.     the user didn’t cancel from a save dialog. This result is handy when
  535.     the user quits an application, but then cancels the save of a document
  536.     associated with a window. */
  537.  
  538. #pragma segment Main
  539. Boolean DoCloseWindow(WindowPtr window)
  540. {
  541.     if ( IsDAWindow(window) )
  542.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  543.     else if ( IsAppWindow(window) )
  544.         CloseWindow(window);
  545.     return true;
  546. } /*DoCloseWindow*/
  547.  
  548.  
  549. /**************************************************************************************
  550. *** 1.01 DoCloseBehind(window) was removed ***
  551.  
  552.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  553.     and not having to worry about updating the windows, but it suffered
  554.     from a fatal flaw. If a desk accessory owned two windows, it would
  555.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  556.     got around to calling DoCloseWindow for that other window that was already
  557.     closed, things would go very poorly. Another option would be to have a
  558.     procedure, GetRearWindow, that would go through the window list and return
  559.     the last window. Instead, we decided to present the standard approach
  560.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  561.     has a potential benefit in that the window whose document needs to be saved
  562.     may be visible since it is the front window, therefore decreasing the
  563.     chance of user confusion. For aesthetic reasons, the windows in the
  564.     application should be checked for updates periodically and have the
  565.     updates serviced.
  566. **************************************************************************************/
  567.  
  568.  
  569. /* Clean up the application and exit. We close all of the windows so that
  570.  they can update their documents, if any. */
  571.  
  572. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  573.     shell, but will return instead. */
  574.  
  575. #pragma segment Main
  576. void Terminate()
  577. {
  578.     ExitToShell();                            /* exit if no cancellation */
  579. } /*Terminate*/
  580.  
  581.  
  582. /*    Set up the whole world, including global variables, Toolbox managers,
  583.     and menus. We also create our one application window at this time.
  584.     Since window storage is non-relocateable, how and when to allocate space
  585.     for windows is very important so that heap fragmentation does not occur.
  586.     Because Sample has only one window and it is only disposed when the application
  587.     quits, we will allocate its space here, before anything that might be a locked
  588.     relocatable object gets into the heap. This way, we can force the storage to be
  589.     in the lowest memory available in the heap. Window storage can differ widely
  590.     amongst applications depending on how many windows are created and disposed. */
  591.  
  592. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  593.     this module. If an error is detected, instead of merely doing an ExitToShell,
  594.     which leaves the user without much to go on, we call AlertUser, which puts
  595.     up a simple alert that just says an error occurred and then calls ExitToShell.
  596.     Since there is no other cleanup needed at this point if an error is detected,
  597.     this form of error- handling is acceptable. If more sophisticated error recovery
  598.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  599.  
  600. #pragma segment Initialize
  601. void Initialize()
  602. {
  603.     Handle        menuBar;
  604.     WindowPtr    window;
  605.     long        total, contig;
  606.     EventRecord event;
  607.     short        count;
  608.  
  609.     gInBackground = false;
  610.  
  611.     InitGraf((Ptr) &qd.thePort);
  612.     InitFonts();
  613.     InitWindows();
  614.     InitMenus();
  615.     TEInit();
  616.     InitDialogs(nil);
  617.     InitCursor();
  618.     
  619.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  620.          if you are using it. */
  621.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  622.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  623.         of checking for port availability themselves. */
  624.     
  625.     /*    This next bit of code is necessary to allow the default button of our
  626.         alert be outlined.
  627.         1.02 - Changed to call EventAvail so that we don't lose some important
  628.         events. */
  629.      
  630.     for (count = 1; count <= 3; count++)
  631.         EventAvail(everyEvent, &event);
  632.     
  633.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  634.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  635.         call to SysEnvirons by calling it after initializing AppleTalk. */
  636.      
  637.     SysEnvirons(kSysEnvironsVersion, &gMac);
  638.     
  639.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  640.     
  641.     if (gMac.machineType < 0) AlertUser();
  642.     
  643.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  644.         in TrapAvailable if a tool trap value is out of range. */
  645.         
  646.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  647.  
  648.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  649.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  650.         MultiFinder we needed. This did not work well because it assumed too much about
  651.         the relationship between what we asked MultiFinder for and what we would actually
  652.         get back, as well as how to measure it. Instead, we will use an alternate
  653.         method comprised of two steps. */
  654.      
  655.     /*    It is better to first check the size of the application heap against a value
  656.         that you have determined is the smallest heap the application can reasonably
  657.         work in. This number should be derived by examining the size of the heap that
  658.         is actually provided by MultiFinder when the minimum size requested is used.
  659.         The derivation of the minimum size requested from MultiFinder is described
  660.         in Sample.h. The check should be made because the preferred size can end up
  661.         being set smaller than the minimum size by the user. This extra check acts to
  662.         insure that your application is starting from a solid memory foundation. */
  663.      
  664.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  665.     
  666.     /*    Next, make sure that enough memory is free for your application to run. It
  667.         is possible for a situation to arise where the heap may have been of required
  668.         size, but a large scrap was loaded which left too little memory. To check for
  669.         this, call PurgeSpace and compare the result with a value that you have determined
  670.         is the minimum amount of free memory your application needs at initialization.
  671.         This number can be derived several different ways. One way that is fairly
  672.         straightforward is to run the application in the minimum size configuration
  673.         as described previously. Call PurgeSpace at initialization and examine the value
  674.         returned. However, you should make sure that this result is not being modified
  675.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  676.         PurgeSpace. Make sure to remove that call before shipping, though. */
  677.     
  678.     /* ZeroScrap(); */
  679.  
  680.     PurgeSpace(&total, &contig);
  681.     if (total < kMinSpace) AlertUser();
  682.  
  683.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  684.         to check memory is that we can now give the user an alert to tell him/her what
  685.         happened. Although it is possible that the memory situation could be worsened by
  686.         displaying an alert, MultiFinder would gracefully exit the application with
  687.         an informative alert if memory became critical. Here we are acting more
  688.         in a preventative manner to avoid future disaster from low-memory problems. */
  689.         
  690.     gCommandsWindow = GetNewDialog(1000, nil, (WindowPtr) -1);
  691.  
  692.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  693.     if ( menuBar == nil ) AlertUser();
  694.     SetMenuBar(menuBar);                    /* install menus */
  695.     DisposHandle(menuBar);
  696.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  697.     DrawMenuBar();
  698.     
  699. } /*Initialize*/
  700.  
  701.  
  702. /*    Check to see if a window belongs to the application. If the window pointer
  703.     passed was NIL, then it could not be an application window. WindowKinds
  704.     that are negative belong to the system and windowKinds less than userKind
  705.     are reserved by Apple except for windowKinds equal to dialogKind, which
  706.     mean it is a dialog.
  707.     1.02 - In order to reduce the chance of accidentally treating some window
  708.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  709.     is userKind. If you add different kinds of windows to Sample you'll need
  710.     to change how this all works. */
  711.  
  712. #pragma segment Main
  713. Boolean IsAppWindow(WindowPtr window)
  714. {
  715.     short        windowKind;
  716.  
  717.     if ( window == nil )
  718.         return false;
  719.     else {    /* application windows have windowKinds = userKind (8) */
  720.         windowKind = ((WindowPeek) window)->windowKind;
  721.         return ( windowKind == userKind );
  722.     }
  723. } /*IsAppWindow*/
  724.  
  725.  
  726. /* Check to see if a window belongs to a desk accessory. */
  727.  
  728. #pragma segment Main
  729. Boolean IsDAWindow(WindowPtr window)
  730. {
  731.     if ( window == nil )
  732.         return false;
  733.     else    /* DA windows have negative windowKinds */
  734.         return ( ((WindowPeek) window)->windowKind < 0 );
  735. } /*IsDAWindow*/
  736.  
  737.  
  738. /*    Check to see if a given trap is implemented. This is only used by the
  739.     Initialize routine in this program, so we put it in the Initialize segment.
  740.     The recommended approach to see if a trap is implemented is to see if
  741.     the address of the trap routine is the same as the address of the
  742.     Unimplemented trap. */
  743. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  744.     if a ToolTrap is out of range of a pre-MacII ROM. */
  745.  
  746. #pragma segment Initialize
  747. Boolean TrapAvailable(short tNumber, TrapType tType)
  748. {
  749.     if ( ( tType == ToolTrap ) &&
  750.         ( gMac.machineType > envMachUnknown ) &&
  751.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  752.         tNumber = tNumber & 0x03FF;
  753.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  754.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  755.     }
  756.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  757. } /*TrapAvailable*/
  758.  
  759.  
  760. /*    Display an alert that tells the user an error occurred, then exit the program.
  761.     This routine is used as an ultimate bail-out for serious errors that prohibit
  762.     the continuation of the application. Errors that do not require the termination
  763.     of the application should be handled in a different manner. Error checking and
  764.     reporting has a place even in the simplest application. The error number is used
  765.     to index an 'STR#' resource so that a relevant message can be displayed. */
  766.  
  767. #pragma segment Main
  768. void AlertUser()
  769. {
  770.     short        itemHit;
  771.  
  772.     SetCursor(&qd.arrow);
  773.     itemHit = Alert(rUserAlert, nil);
  774.     ExitToShell();
  775. } /* AlertUser */
  776.